// Redux store 配置文件
import { configureStore } from '@reduxjs/toolkit';
// 导入主题和语言的 reducer
import themeReducer from './slices/themeSlice';
import languageReducer from './slices/languageSlice';
import authReducer from './slices/authSlice';

// 本地持久化 key
const PERSIST_KEY = 'dh_prefs_v1';

// 读取持久化的初始状态
function loadPersistedState(): any | undefined {
	if (typeof window === 'undefined') return undefined;
	try {
		const raw = localStorage.getItem(PERSIST_KEY);
		if (!raw) return undefined;
		const parsed = JSON.parse(raw);
		return parsed && typeof parsed === 'object' ? parsed : undefined;
	} catch {
		return undefined;
	}
}

// 持久化当前状态（仅保存必要片段）
function persistState(state: any) {
	if (typeof window === 'undefined') return;
	try {
		const toSave = JSON.stringify({
			theme: { currentTheme: state.theme?.currentTheme },
			language: { currentLanguage: state.language?.currentLanguage },
			auth: state.auth?.user ? { user: state.auth.user } : { user: null },
		});
		localStorage.setItem(PERSIST_KEY, toSave);
	} catch {
		// 忽略存储失败
	}
}

const preloadedState = loadPersistedState();

// 配置 Redux store（带持久化）
export const store = configureStore({
	reducer: {
		theme: themeReducer,
		language: languageReducer,
		auth: authReducer,
	},
	preloadedState,
	devTools: true,
});

// 订阅变更以写回 localStorage
store.subscribe(() => {
	persistState(store.getState());
});

// 导出类型
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

